package com.example.weather.sdk;

import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.util.SparseArray;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.example.weather.R;
import com.example.weather.utils.IconUtils;
import com.google.gson.Gson;
import com.qweather.sdk.bean.air.AirNowBean;
import com.qweather.sdk.bean.base.Code;
import com.qweather.sdk.bean.base.Lang;
import com.qweather.sdk.bean.geo.GeoBean;
import com.qweather.sdk.bean.weather.WeatherNowBean;
import com.qweather.sdk.view.QWeather;

import java.time.LocalTime;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * 天气API来自和风天气：https://www.qweather.com
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private TextView tvCity;
    private ImageView ivIcon;
    private TextView tvWeather;
    private TextView tvTemp;
    private TextView tvWind;
    private TextView tvPm;
    private RelativeLayout mainLayout;

    private SparseArray<String> cities;
    private Map<String, String> imageUrls;
    private String currentImageUrl;
    private String currentCity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        initView();
        initData();
    }

    private void initView() {
        mainLayout = findViewById(R.id.main_layout);
        tvCity = findViewById(R.id.tv_city);
        ivIcon = findViewById(R.id.iv_icon);
        tvWeather = findViewById(R.id.tv_weather);
        tvTemp = findViewById(R.id.tv_temp);
        tvWind = findViewById(R.id.tv_wind);
        tvPm = findViewById(R.id.tv_pm);

        findViewById(R.id.btn_nj).setOnClickListener(this);
        findViewById(R.id.btn_bj).setOnClickListener(this);
        findViewById(R.id.btn_sh).setOnClickListener(this);
        findViewById(R.id.btn_gz).setOnClickListener(this);
    }

    private void initData() {
        cities = new SparseArray<>();
        cities.put(R.id.btn_nj, "南京");
        cities.put(R.id.btn_bj, "北京");
        cities.put(R.id.btn_sh, "上海");
        cities.put(R.id.btn_gz, "广州");
        currentCity = cities.get(R.id.btn_nj);

        imageUrls = new HashMap<>();
        imageUrls.put("多云", "https://b.zol-img.com.cn/sjbizhi/images/10/320x510/1576120745780.jpg");
        imageUrls.put("晴", "https://sjbz-fd.zol-img.com.cn/t_s320x510c5/g5/M00/0F/09/ChMkJlfJQWSIIEmVAAQzGYKI3fwAAU7cwLGCn8ABDMx195.jpg");
        imageUrls.put("雨", "https://b.zol-img.com.cn/sjbizhi/images/10/320x510/157367915321.jpg");
        imageUrls.put("阴", "https://sjbz-fd.zol-img.com.cn/t_s320x510c5/g6/M00/04/08/ChMkKV8iKQSIQf3QABP2dG0tSfEAAASAAFHVTwAE_aM847.jpg");
        imageUrls.put("默认", "https://sjbz-fd.zol-img.com.cn/t_s320x510c5/g5/M00/02/00/ChMkJl3xtFSIMSpNABawKeTgRp4AAvtLAEsyP8AFrBB136.jpg");

        getDataByCity(currentCity);
    }

    private void loadBackground(String imageUrl) {
        Glide.with(MainActivity.this)
                .asBitmap()
                .load(imageUrl)
                .into(new CustomTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                        final BitmapDrawable drawable = new BitmapDrawable(getResources(), resource);
                        mainLayout.setBackground(drawable);
                    }

                    @Override
                    public void onLoadCleared(@Nullable Drawable placeholder) {
                        mainLayout.setBackgroundResource(R.drawable.default_img);
                    }
                });
    }

    @Override
    public void onClick(View view) {
        currentCity = cities.get(view.getId());
        getDataByCity(currentCity);
    }


    private void getDataByCity(String cityName) {
        QWeather.getGeoCityLookup(this, cityName, new QWeather.OnResultGeoListener() {
            @Override
            public void onError(Throwable throwable) {
                Log.e("MainActivity", "getCityId onError: " + throwable.toString());
            }

            @Override
            public void onSuccess(GeoBean geoBean) {
                Log.i("MainActivity", "getCityId onSuccess: " + new Gson().toJson(geoBean));
                if (Code.OK.getCode().equalsIgnoreCase(geoBean.getStatus())) {
                    GeoBean.LocationBean locationBean = geoBean.getLocationBean().get(0);
                    if (locationBean != null) {
                        getNow(locationBean.getId());
                    }
                } else {
                    //在此查看返回数据失败的原因
                    String status = geoBean.getStatus();
                    Code code = Code.toEnum(status);
                    Log.i("MainActivity", "failed code: " + code);
                }
            }
        });
    }

    private void getNow(String cityId) {
        QWeather.getWeatherNow(this, cityId, new QWeather.OnResultWeatherNowListener() {
            @Override
            public void onError(Throwable throwable) {
                Log.e("MainActivity", "getWeather onError: " + throwable.toString());
            }

            @Override
            public void onSuccess(WeatherNowBean weatherNowBean) {
                Log.i("MainActivity", "getWeather onSuccess: " + new Gson().toJson(weatherNowBean));
                if (Code.OK.getCode().equalsIgnoreCase(weatherNowBean.getCode())) {
                    WeatherNowBean.NowBaseBean now = weatherNowBean.getNow();

                    String condCode = now.getIcon();
                    int hour = 0;
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                        LocalTime nowTime = LocalTime.now();
                        hour = nowTime.getHour();
                    } else {
                        final Calendar today = Calendar.getInstance();
                        hour = today.get(Calendar.HOUR_OF_DAY);
                    }
                    if (hour > 6 && hour < 18) {
                        ivIcon.setImageResource(IconUtils.getDayIconDark(condCode));
                    } else {
                        ivIcon.setImageResource(IconUtils.getNightIconDark(condCode));
                    }
                    tvCity.setText(currentCity);
                    tvWeather.setText(now.getText());
                    tvTemp.setText(now.getTemp() + "℃");
                    tvWind.setText(now.getWindDir() + now.getWindScale() + "级");
                    currentImageUrl = imageUrls.get(now.getText());
                    currentImageUrl = currentImageUrl != null ? currentImageUrl : imageUrls.get("默认");
                    loadBackground(currentImageUrl);
                }
            }
        });
        QWeather.getAirNow(this, cityId, Lang.ZH_HANS, new QWeather.OnResultAirNowListener() {
            @Override
            public void onError(Throwable throwable) {
                Log.e("MainActivity", "getAirNow onError: " + throwable.toString());
            }

            @Override
            public void onSuccess(AirNowBean airNowBean) {
                Log.i("MainActivity", "getAirNow onSuccess: " + new Gson().toJson(airNowBean));
                if (Code.OK.getCode().equalsIgnoreCase(airNowBean.getCode())) {
                    AirNowBean.NowBean now = airNowBean.getNow();
                    tvPm.setText("空气" + now.getCategory());
                }
            }
        });
    }
}